var appUtil = require('../common/app_util.js');
var errCode = require('../common/err_code.js');
var userDao = require('../dao/user.js');
var roleDao = require('../dao/role.js');

var service = {};
module.exports = service;

var __ENUM_USER_TYPE = {
  CLIENT_NOT_VERIFY: 'client_not_verify', /* 未验证的用户*/
  MERCHANT_NOT_VERIFY: 'merchant_not_verify' /* 未验证的商家*/
};
/**
 * 注册
 */
service.register = function *(userInfo) {
  var checkRes = checkUserInfo(userInfo);
  if (checkRes.errcode != 0) {
    return checkRes;
  }
  var user2 = checkRes.data;

  // get role
  var userType = __ENUM_USER_TYPE.CLIENT_NOT_VERIFY;
  if (user2.type == 'merchant') userType = __ENUM_USER_TYPE.MERCHANT_NOT_VERIFY;
  var retObjRole = yield roleDao.findOneByWhere({where: {name: userType}});
  var role = retObjRole.getData();
  /* error handle if role null, should be error */

  // create new user
  user2.roleid = role.id;
  user2.createdAt = new Date(appUtil.fmtDate());
  var retObjUser = yield userDao.create(user2);
  if (retObjRole.isOk()) {
    // todo 添加验证信息
  }
  return retObjUser;
};

/**
 * reids + expired
 * 但是为了避免复杂，采用应用缓存 token:userObj
 */
var __tokenList = {};
/**/
/**
 * 登录
 * @param json
 */
service.login = function*(json) {
  var email = json.email;
  var password = json.password;
  var retObjUser = yield userDao.findOneByWhere({where: {email: email, password: password}});
  var user = retObjUser.getData();
  if (user) {
    var token = appUtil.md5(email);
    __tokenList[token] = user;
    return appUtil.fout({token: token});
  } else {
    return appUtil.ferror(errCode.E_LOGIN);
  }
};
/**
 * 生产验证信息
 */
service.verifyUrlGenerator = function () {

};

function checkUserInfo(userInfo) {
  // TODO 输入检测
  // TODO 权限检测
  return appUtil.fout(userInfo);
}